﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using MayhemCore;
using MayhemWpf.ModuleTypes;
using MayhemWpf.UserControls;
using KinectModule.Wpf;
using KinectModule.KinectHelpers;
using System.Threading;
using System.Windows.Threading;
using System.Text.RegularExpressions;

namespace KinectModule.Events
{
    [DataContract]
    [MayhemModule("Motion Detection", "Kinect integration")]
    public class KinectMove : EventBase, IWpfConfigurable
    {
        [DataMember]
        private MotionType _motionType;
        private KinectManager _manager;
        private Thread _mainThread;

        public WpfConfiguration ConfigurationControl
        {
            get { return new KinectMoveConfig(); }
        }

        protected override void OnAfterLoad()
        {
            _manager = new KinectManager();
            _mainThread = Thread.CurrentThread;
        }

        protected override void OnEnabling(EnablingEventArgs e)
        {
            Dispatcher.FromThread(_mainThread).Invoke((Action)(() => 
            { 
                _manager.AddHandler(_motionType, Trigger); 
            }));
        }

        public void OnSaved(WpfConfiguration configurationControl)
        {
            _motionType = (configurationControl as KinectMoveConfig).MotionType;
        }

        public string GetConfigString()
        {
            return "Motion: " + Regex.Replace(_motionType.ToString(), "((?<=\\p{Ll})\\p{Lu})|((?!\\A)\\p{Lu}(?>\\p{Ll}))", " $0");
        }

        protected override void OnDisabled(DisabledEventArgs e)
        {
            _manager.StopKinect();
        }
    }
}
